import {
  ref,
  defineComponent,
  PropType,
  defineProps,
  defineEmits,
  defineExpose,
  watch,
  reactive
} from 'vue';
import RadModal from '@/components/RadModal/index.vue';
import type { SysJobDetail } from '@/api/system/job/model';
import { storeToRefs } from 'pinia';
import {
  FormInstance,
  message,
  Form,
  Row,
  Col,
  FormItem,
  Input,
  RadioGroup,
  RadioButton,
  Textarea,
  InputNumber
} from 'ant-design-vue';
import useFormData from '@/utils/use-form-data';
import { add, update } from '@/api/system/config';
import { Rule } from 'ant-design-vue/es/form';
import { useThemeStore } from '@/store/modules/theme';

// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
const props = defineProps({
  visible: {
    type: [Boolean],
    require: true,
    default: false
  },
  data: {
    type: Object as PropType<SysJobDetail>,
    default: () => {
      return null;
    }
  }
});
const emit = defineEmits({
  done: () => {
    return true;
  },
  cancel: () => {
    return true;
  },
  'update:visible': (visible: boolean) => {
    return visible;
  }
});
// watch(
//   () => props.visible,
//   (visible) => {
//     if (visible) {
//       if (props.data) {
//         assignFields(props.data);
//         isUpdate.value = true;
//       } else {
//         isUpdate.value = false;
//       }
//     } else {
//       resetFields();
//       formRef.value?.clearValidate();
//     }
//   }
// );
const formRef = ref<FormInstance | null>(null);
const ifShow = ref(false);
// 是否是修改
const isUpdate = ref(false);
// 提交状态
const loading = ref(false);
// 表单数据
const { form, resetFields, assignFields } = useFormData<SysJobDetail>({
  id: 0,
  groupName: '',
  jobType: '',
  assemblyName: '',
  description: '',
  concurrent: false,
  includeAnnotations: false,
  properties: '',
  updatedTime: '',
  createType: 0,
  scriptCode: '',
  jobId: ''
});

// 表单验证规则
const rules = reactive<Record<string, Rule[]>>({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入编码',
      type: 'string',
      trigger: 'blur'
    }
  ],
  order: [
    {
      required: true,
      message: '请输入排序',
      type: 'number',
      trigger: 'blur'
    }
  ],
  value: [
    {
      required: true,
      message: '请输入值',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      const saveOrUpdate = isUpdate.value ? update : add;
      saveOrUpdate(form)
        .then((msg) => {
          loading.value = false;
          message.success(msg);
          updateVisible(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {});
};

/* 更新visible */
const updateVisible = (value: boolean) => {
  ifShow.value = value;
  emit('update:visible', value);
};
const openModal = () => {
  ifShow.value = true;
};

export const expose = defineExpose({ openModal });

export default {
  name: 'EditJobDetailModal',
  render() {
    return (
      <RadModal
        v-model:visible={ifShow.value}
        loading={loading.value}
        isUpdate={isUpdate.value}
        title="作业信息"
        onVisible:change={updateVisible}
        onOk={save}
      >
        <Form
          ref="formRef"
          model={form}
          rules={rules}
          label-col={
            styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }
          }
        >
          <Row>
            <Col span="12">
              <FormItem label="作业编号" label-col={{ md: 2 }} name="jobId">
                <Input
                  allow-clear
                  maxlength={20}
                  placeholder="请输入作业编号"
                  value={form.jobId}
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="组名称" label-col={{ md: 2 }} name="groupName">
                <Input
                  allow-clear
                  class="ele-fluid"
                  maxlength={20}
                  placeholder="请输入组名称"
                  value={form.groupName}
                />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="创建类型">
                <RadioGroup
                  size="default"
                  value={form.createType}
                  button-style="solid"
                >
                  <RadioButton value={1}>是</RadioButton>
                  <RadioButton value={2}>否</RadioButton>
                </RadioGroup>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="执行方式">
                <RadioGroup
                  size="default"
                  value="form.concurrent"
                  button-style="solid"
                >
                  <RadioButton value="1">并行</RadioButton>
                  <RadioButton value="2">串行</RadioButton>
                </RadioGroup>
              </FormItem>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span="12">
              <FormItem label="值" name="value">
                <Input allow-clear placeholder="请输入值" value="form.value" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="平台配置">
                <RadioGroup
                  size="default"
                  value="form.sysFlag"
                  button-style="solid"
                >
                  <RadioButton value="1">是</RadioButton>
                  <RadioButton value="2">否</RadioButton>
                </RadioGroup>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="所属分类">
                <Input
                  allow-clear
                  placeholder="请输入所属分类"
                  value="form.groupCode"
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="排序" name="order">
                <InputNumber
                  min="0"
                  max="99999"
                  class="ele-fluid"
                  placeholder="请输入排序号"
                  value="form.order"
                />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="24">
              <FormItem label="备注" label-col={{ md: 2 }}>
                <Textarea
                  rows={4}
                  maxlength={200}
                  placeholder="请输入备注"
                  value="form.remark"
                />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </RadModal>
    );
  }
};
